#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#define NUM_THREAD 6

void * thread_function(void * arg);
pthread_t a_thread[NUM_THREAD];


int main()
{
    int res;
    void * thread_result;
    int lots_of_threads;

    for (lots_of_threads = 0;lots_of_threads < NUM_THREAD; lots_of_threads++){

            res = pthread_create(&(a_thread[lots_of_threads]),NULL,thread_function,&lots_of_threads);
	    //cast to pointer from integer of different size ，意思为指针和整型两种类型的大小不一致。
            
            if (res != 0){
                char * str;
                sprintf(str,"[%d] pthread_create failure",lots_of_threads);
                perror(str);
                exit(EXIT_FAILURE);
            }
            sleep(1);

    }
    printf("Waiting for threads to finish...\n");
    for(lots_of_threads =NUM_THREAD -1;lots_of_threads >=0;lots_of_threads--){
        res = pthread_join(a_thread[lots_of_threads],&thread_result);
        if (res != 0){
                char * str;
                sprintf(str,"[%d] pthread_create failure",lots_of_threads);
                perror(str);
                exit(EXIT_FAILURE);
        }
    }
    printf("All done\n");
    exit(EXIT_SUCCESS);
}

void * thread_function(void * arg)
{
   int my_number = *(int*)arg ;
   int rand_num;

   printf("thread[%d] is running\n",my_number);
   
  rand_num = 1 + (9*rand() / (RAND_MAX + 1.0)) ;

//  sleep(rand_num);
  printf("Bye Form %d\n",my_number);
  pthread_exit(NULL);
}

